<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <title>Title</title>
</head>
<style>
    #clickDiv{
        position: absolute;
        top: 50%;
        left: 50%;
        transform: translate(-50%,-50%);
        width: 200px;
        height: 200px;
        text-align: center;
        line-height: 200px;
        background: pink;
    }
</style>
<body>
<div id="clickDiv">我是一个DIV</div>
</body>
<script>

    function EventListener(obj) {

        let eventObj = {//存取事件名和事件回调函数

        };

        obj.on = function (name, method) {
            if(eventObj.hasOwnProperty(name)){
                eventObj[name].push(method)
            }else {
                eventObj[name] = [method]
            }
        };

        obj.emit = function (name) {//dataChange,{name: "xxxx", age: 18}, "这是一个msg信息"
//            arguments
            let methods = eventObj[name];//[function (newData) {},function (newData, msg) {}]
            for(let i = 0;i<methods.length;i++){
                let curFn = methods[i];//function (newData) {}
                let args = [];
                for(let j=1;j<arguments.length;j++){
                    args.push(arguments[j])
                }
                curFn.apply(this,args)
            }
        };

        obj.off = function (name, method) {
            let methods = eventObj[name];
            for(let i = 0;i<methods.length;i++){
                if(JSON.stringify(methods[i]) === JSON.stringify(method)){
                    methods.splice(i, 1)
                }
            }
        };

        obj.destroy = function () {
            eventObj = {}
        };

        return obj
    }

    globalEventListener = EventListener({});


    //组件1 this
    let obj = {
        name: "clickDiv"
    };
    let dataChangeFn1 = function (newData) {
        obj.name = newData.name;

        console.log("组件1===dataChangeFn1--->",obj)
    };
    let dataChangeFn2 = function (newData, msg) {
        obj.age = newData.age;
        console.log("组件1===msg--->",msg);

        console.log("组件1===dataChangeFn2--->",obj)
    };


    globalEventListener.on("dataChange", dataChangeFn1);
    globalEventListener.on("dataChange", dataChangeFn2);
    globalEventListener.off("dataChange", dataChangeFn2);


    //组件2
    //    this
    let clickDiv = document.getElementById("clickDiv");
    clickDiv.addEventListener("click", function () {

        globalEventListener.emit("dataChange", {
            name: "xxxx",
            age: 18
        }, "这是一个msg信息");
        globalEventListener.emit("dataChange2", "11111")
    });


    //组件3 this
    let obj3 = {
        name: "clickDiv"
    };
    globalEventListener.on("dataChange2", function (newData) {
        obj3.name = newData;

        console.log("组件3===dataChange2--obj3->",obj3)
    });

</script>
</html>